<template>
	<el-upload :action="'#'" :http-request="onFileUpload" :accept="fileTypes == null ? '' : fileTypes.join(',')"
		:show-file-list="false" :disabled="disabled" :before-upload="beforeUpload" :multiple="true">
		<slot></slot>
	</el-upload>
</template>

<script>
// import {CryptoUtil} from "@/api/cryptoUtil";

export default {
	name: "fileUpload",
	data() {
		return {
			loading: null,
			uploadHeaders: {
				"accessToken": sessionStorage.getItem('accessToken')
			}
		}
	},
	props: {
		action: {
			type: String,
			required: false
		},
    encrypted: {
			type: Boolean,
      default: true,
			required: false
		},
		fileTypes: {
			type: Array,
			default: null
		},
		maxSize: {
			type: Number,
			default: null
		},
		showLoading: {
			type: Boolean,
			default: false
		},
		disabled: {
			type: Boolean,
			default: false
		}
	},
	methods: {
		async onFileUpload(file) {
			// 展示加载条
			if (this.showLoading) {
				this.loading = this.$loading({
					lock: true,
					text: 'Uploading...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
			}

      // const encryptFile = (file) => {
      //   return new Promise((resolve, reject) => {
      //     var code = 0
      //     var keyObj = {
      //       code,
      //       key: '12345678'
      //     }
      //     var reader = new FileReader();
      //     reader.readAsArrayBuffer(file);
      //     reader.onload = () => {
      //       console.log('reader', reader.result);
      //       var fileEncrypted = new CryptoUtil(code).encryptFile(reader.result, keyObj.key, file)
      //       resolve(fileEncrypted)
      //     }
      //   });
      // }

      file = file.file

      let formData = new FormData()
      if (this.encrypted) {
        // formData.append('file',await encryptFile(file))
        // formData.append('file',await this.$store.dispatch("encryptFile", {file}))

        var cryptoInstance = this.$store.getters.cryptoInstance();
        var encryptFile = await cryptoInstance.cryptoUtil.encryptFileReal(cryptoInstance, file);
        formData.append('file', encryptFile)

      } else {
        formData.append('file',file)
      }

      this.$http({
        url: this.action,
        data: formData,
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then((data) => {
        this.$emit("success", data, file);
      }).catch((e) => {
        this.$emit("fail", e, file);
      }).finally(() => {
        this.loading && this.loading.close();
      })

		},
		beforeUpload(file) {
			// 校验文件类型
			if (this.fileTypes && this.fileTypes.length > 0) {
				let fileType = file.type;
				let t = this.fileTypes.find((t) => t.toLowerCase() === fileType);
				if (t === undefined) {
					this.$message.error(`The file format is incorrect. Please upload the file in the following format:${this.fileTypes.join("、")}`);
					return false;
				}
			}
			// 校验大小
			if (this.maxSize && file.size > this.maxSize) {
				this.$message.error(`The file size cannot exceed ${this.fileSizeStr}!`);
				return false;
			}
			this.$emit("before", file);
			return true;
		}
	},
	computed: {
		fileSizeStr() {
			if (this.maxSize > 1024 * 1024) {
				return Math.round(this.maxSize / 1024 / 1024) + "M";
			}
			if (this.maxSize > 1024) {
				return Math.round(this.maxSize / 1024) + "KB";
			}
			return this.maxSize + "B";
		}
	}
}
</script>

<style></style>